
package com.tiem_files.controller.user;

import com.tiem_files.common.Constant;
import com.tiem_files.controller.BaseController;
import com.tiem_files.model.User;
import com.tiem_files.model.UserFocus;
import com.tiem_files.service.DeptService;
import com.tiem_files.service.UserService;
import com.tiem_files.service.impl.DeptServiceImpl;
import com.tiem_files.service.impl.UserServiceImpl;
import com.tiem_files.utils.PageUtil;
import com.tiem_files.utils.StrUtil;
import javafx.scene.layout.Pane;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.omg.CORBA.MARSHAL;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

@WebServlet("/user/*")
public class UserController extends BaseController {
    private UserService userService=new UserServiceImpl();
    private DeptService deptService=new DeptServiceImpl();


    public void look(HttpServletRequest req, HttpServletResponse resp){
        try {
            String id = req.getParameter("userId");
          Map<String,Object> map = userService.getUserInfo(id);
          req.setAttribute("userInfo",map);
          req.setAttribute("deptList",deptService.getAll());
          req.getRequestDispatcher("/assets/html/user_look.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void  getUsers(HttpServletRequest req, HttpServletResponse resp){
        try {
            String page = req.getParameter("page");
            String name = req.getParameter("searchName");
            int currentPage = 1;
            if ( null  != page){
                currentPage = Integer.parseInt(page);
            }
            //从会话拿到当前登录的账户信息
            Map baseInfo = (Map)req.getSession().getAttribute("userBaseInfo");
            String userId = baseInfo.get("user_id").toString();
            List<Map<String, Object>> userList = userService.getUserList(userId,currentPage, name);
            req.setAttribute("userList",userList);
            long totalCount = userService.getUserCount(name);
            long totalPage = PageUtil.getTotalPage(totalCount);
            long startPage = PageUtil.getStratPage(currentPage);
            long endPage = PageUtil.getEndPage(currentPage,totalCount);
            req.setAttribute("currentPage",currentPage);
            req.setAttribute("searchName",name);
            req.setAttribute("totalCount",totalCount);
            req.setAttribute("totalPage",totalPage);
            req.setAttribute("startPage",startPage);
            req.setAttribute("endPage",endPage);


            req.getRequestDispatcher("/assets/html/user.jsp").forward(req,resp);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void followUser(HttpServletRequest req, HttpServletResponse resp){
        try {
            String date;
            String ufId = req.getParameter("ufId");
            String userId = getUserId(req);
            if (userId.equals(ufId)){
                date ="不能关注自己";
            }else {
                //检查是否是重复关注
              UserFocus focus= userService.getFollowUser(userId,ufId);
                if (focus != null){
                    date = "不能重复关注";
                }else {
                    boolean b = userService.followUser(userId, ufId);
                    if (b){
                        date = "1";
                    }else {
                        date ="关注失败";
                    }
                }
            }
            resp.getWriter().write(date);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public void unFollowUser(HttpServletRequest req, HttpServletResponse resp){
            try {
                String date;
                String ufId = req.getParameter("ufId");
                String userId = getUserId(req);
                UserFocus focus= userService.getFollowUser(userId,ufId);
                if (focus != null){
                  boolean b = userService.unFollowUser(focus.getId());
                  if (b){
                      date = "1";
                  }else {
                      date = "取消关注失败";
                  }
                }else {
                    date = "操作频繁 请稍后再试!";
                }
                resp.getWriter().write(date);
            }catch (Exception e){
                e.printStackTrace();
            }
    }

    public void uploadFile(HttpServletRequest req, HttpServletResponse resp){
        try {
            InputStream is =null;
            String fileName = StrUtil.getUUID()+Constant.FILE_SUFFIX ;
            FileOutputStream fos  =null;
            try {
                ServletFileUpload servletFileUpload = new ServletFileUpload(new DiskFileItemFactory());
                List<FileItem> items = servletFileUpload.parseRequest(req);
            if (!items.isEmpty()){
                FileItem file= items.get(0);
                String name =file.getName();
                if (!name.contains("jpg")){
                    resp.getWriter().write(req.getContextPath() + Constant.DEFAULT_PATH);
                    return;
                }
                 is = file.getInputStream();
                 fos  = new FileOutputStream(Constant.FILE_PATH + fileName);
                byte[] bytes = new byte[4 * 1024];
                int len ;
                while ((len = is.read(bytes)) != -1){
                    fos.write(bytes,0,len);
                }
            }
            }catch (FileUploadException  | IOException e){
                e.printStackTrace();
            }finally {
                if (fos != null){
                    fos.close();
                }
                if (is != null){
                    is.close();
                }
            }
            //更新到数据库
            String userId = getUserId(req);
            userService.uploadImg(userId,Constant.IN_PATH+fileName);
            Map<String,Object> map = userService.getUserInfo(getUserMame(req));
            req.setAttribute("userInfo",map);
            resp.getWriter().write(Constant.IN_PATH+fileName);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
